<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:34
 */

namespace app\home\controller;

use app\admin\model\Config;
use app\home\model\CreditRecord;
use app\admin\model\TaskCategory;
use app\home\model\Member;
use app\admin\model\InvitationRebateRecord;
use think\Db;
use think\Log;

class Mytaskaudit extends Base {
    
    public $kc_money = 0;
    
    public function _initialize()
    {
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['kc_money'])){
                $this->kc_money = round(floatval($setting['kc_money']/100),2);
            }
        }
    }
    
    public function index($id = 0){
        $params = array_trim(request()->get());
        
        $request=request();
        $id=$request->param('id');
        $join_status=$request->param('join_status');

        $status_name='';
        switch ($join_status){
            case 1:
            $status_name='lock';
            break;
            case 2:
            $status_name='wait';
            break;
            case 3:
            $status_name='pass';
            break;
            case 4:
            $status_name='nopass';
            break;
        }
        if($status_name){
            $params['category_type']=$status_name;
        }

        $this->assign('join_status',$join_status);
        
        $data = $this->_get_data($id, $params);
        $this->assign('id',$id);
        
        $data = $this->_get_data($id, $params);
        return $this->fetch('index', $data);
    }

    public function category($id = 0) {
        $params = array_trim(request()->get());
        $params['category_type'] = trim(params('t'));
        $data = $this->_get_data($id, $params);

        return $this->fetch('index', $data);
    }

    private function _get_data($id, $params = array()) {
        $member = $this->checkLogin();

        $id = floor(trim(params('id')));
        if(!check_id($id)){
            message('任务ID错误','','error');
        }
        $item = \app\home\model\Task::getInfoById($id);
        if(empty($item)){
            message('任务不存在','','error');
        }

        if(empty($this->member['uid']) || $item['uid'] != $this->member['uid']){
            message('任务不存在','','error');
        }

        $params['task_id'] = $item['id'];
        $params['uid'] = $member['uid'];

        $categories = TaskCategory::getListByKey();

        $pszie = 15;
        $tasks = \app\home\model\MyTaskAudit::getListByParams($params, $pszie);
        if(!empty($tasks)){
            foreach ($tasks as &$v){
                $v['category_icon'] = isset($categories[$v['category_id']]) ? to_media($categories[$v['category_id']]['thumb']) : "";
                 $useinfo=Db::name("member")->where("uid = {$v['join_uid']}")->select();
               
                $v['avatar']=$useinfo?$useinfo[0]['avatar']:'';
            }
        }
        if(request()->isAjax()){
            if(empty($tasks)){
                message('没有更多信息','','error');
            }

            $html = $this->fetch('_list', [
                'tasks' => $tasks
            ]);
            message($html,'','success');
        }
        $count = \app\home\model\MyTaskAudit::getCountByParams($params);
        $pageCount = ceil($count/$pszie);
        return [
            'item' => $item,
            'category_type' => isset($params['category_type']) ? $params['category_type'] : 'all',
            'tasks' => $tasks,
            'count' => $count,
            'pageCount' => $pageCount
        ];
    }
   
    public function view() {
        return $this->detail(1);
    }

    public function detail($isview = 0) {
        $member = $this->checkLogin();

        $id = floor(trim(params('id')));
        if(!check_id($id)){
            message('审核ID错误','','error');
        }
        $joinInfo = \app\home\model\TaskJoin::getInfoById($id);
        if(empty($joinInfo)){
            message('审核不存在','','error');
        }

        if(!empty($joinInfo['thumbs'])){
            $joinInfo['thumbs'] = unserialize($joinInfo['thumbs']);
        }

        $item = \app\home\model\Task::getInfoById($joinInfo['task_id']);
        if(empty($item)){
            message('任务不存在','','error');
        }

        if(empty($this->member['uid']) || $item['uid'] != $this->member['uid']){
            message('任务不存在','','error');
        }

        $joinMember = Member::getUserInfoById($joinInfo['uid']);
        if(empty($member)){
            message('会员信息不存在','/home/auth/login.html','error');
        }

        $item['audit_num'] = \app\home\model\TaskJoin::getAuditNumById($item['id']);
      

        return $this->fetch(__FUNCTION__,[
            'item' => $item,
            'joinInfo' => $joinInfo,
            'joinMember' => $joinMember,
            'isview' => $isview,
        ]);
    }

    public function audit() {
        $member = $this->checkLogin();
        $setting = ['invitation_rebate' => 0];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['invitation_rebate'])){
                $setting['invitation_rebate'] = round(floatval($setting['invitation_rebate']/100),2);
            }
        }
        $id = floor(trim(params('id')));
        if(!check_id($id)){
            message('审核ID错误','','error');
        }
        $joinInfo = \app\home\model\TaskJoin::getInfoById($id);
       
        if(empty($joinInfo)){
            message('审核不存在','','error');
        }
      if($joinInfo['status'] == 3 || $joinInfo['status'] == 4){
         message('任务已审核','','error');
      }

        if(!empty($joinInfo['thumbs'])){
            $joinInfo['thumbs'] = unserialize($joinInfo['thumbs']);
        }

        $params = \app\home\model\Task::getInfoById($joinInfo['task_id']);
        if(empty($params)){
            message('任务不存在','','error');
        }

        if(empty($this->member['uid']) || $params['uid'] != $this->member['uid']){
            message('任务不存在','','error');
        }

        $joinMemberInfo = Member::getUserInfoById($joinInfo['uid']);
        if (!$joinMemberInfo){
            message('任务会员不存在','','error');
        }
        $insert_task_id = $joinInfo['task_id'];

        Db::startTrans();

        $update = array(
            'status' => 3,
            'audit_time' => TIMESTAMP,
            'update_time' => TIMESTAMP
        );
        $status = \app\home\model\TaskJoin::updateInfoById($id, $update);
        if(!$status){
            Db::rollback();
            message('审核失败:-1','','error');
        }
        
        if($params['give_credit1']>0 || $params['unit_price']>0){
            $give_credit1 = $params['give_credit1'];
           // $unit_price = $params['unit_price'];
            
            $unit_price = $params['unit_price'] - $params['unit_price']*$this->kc_money;
            
            
          //VIP赠送积分
				 if($joinMemberInfo['level'] != 1){
                   // $give_credit1 = $params['give_credit1']*$setting['zengjifen'];
                  }
          
            ////////////////////////////////////////////////
            //$taskinfos = Db::name("task")->where("id = {$params['id']}")->find();
            $mems = Db::name("member")->where("uid = {$joinInfo['uid']}")->find();
			 
            if($mems['level'] >1){
                $gory = Db::name("member_level")->where("level = {$mems['level']}")->find();

            }
            ///////////////////////////////////////////////
            //有推荐人，做完任务审核通过需要按后台设置比例分成给推荐人
			

            $taskService = \think\Loader::model("Task", 'service');
            $taskService->invitationFirstTaskAward($joinMemberInfo, $params);


            //分别记录积分和余额记录
            if($give_credit1>0){
                $status2 = CreditRecord::addInfo([
                    'uid' => $joinInfo['uid'],
                    'type' => 'credit1',
                    'num' => $give_credit1,
                    'title' => '审核任务',
                    'remark' => "任务[" . $params['id'] . "]-" . $params['title'] . "审核成功，奖励{$give_credit1}积分。",
                    'create_time' => TIMESTAMP
                ]);
                if(!$status2){
                    Db::rollback();
                    message('审核失败:-3','','error');
                }
              	$my_credit1['pet_need_credit'] = $mems['pet_need_credit']+$give_credit1;
             	$my_credit1['credit1'] = $mems['credit1']+$give_credit1;	
               
              	db('member')->where('uid',$joinInfo['uid'])->update($my_credit1);
            }  
	
			 if($mems['level'] >1){
               
				$status1 = Member::updateCreditById($joinInfo['uid'], $give_credit1, $unit_price+$gory['butie']);
				
				if(!$status1){
		                Db::rollback();
		                message('审核失败:-9','','error');
		            }
		            

	            if($unit_price>0){
	                $ttsive = $unit_price+$gory['butie'];
	                $status3 = CreditRecord::addInfo([
	                    'uid' => $joinInfo['uid'],
	                    'type' => 'credit2',
	                    'num' => $ttsive,
	                    'title' => '审核任务',
	                    'remark' => "任务[" . $params['id'] . "]-" . $params['title'] . "审核成功，奖励{$unit_price}元。",
	                    'create_time' => TIMESTAMP
	                ]);
	                if(!$status3){
	                    Db::rollback();
	                    message('审核失败:-6','','error');
	                }
	              
	            }
            
            }else{
			
				  $status1 = Member::updateCreditById($joinInfo['uid'], 0, $unit_price);
		
		            if(!$status1){
		                Db::rollback();
		                message('审核失败:-2','','error');
		            }
				  if($unit_price>0){
		                $status3 = CreditRecord::addInfo([
		                    'uid' => $joinInfo['uid'],
		                    'type' => 'credit2',
		                    'num' => $unit_price,
		                    'title' => '审核任务',
		                    'remark' => "任务[" . $params['id'] . "]-" . $params['title'] . "审核成功，奖励{$unit_price}元。",
		                    'create_time' => TIMESTAMP
		                ]);
		                if(!$status3){
		                    Db::rollback();
		                    message('审核失败:-7','','error');
		                }
		            }
				
			}
			if($mems['over_task_num'] ==0 ){
				         	//首次完成任务给上级奖励
				         	$credit2_dady = $setting['invitation_first_task_award'];
				         	if($mems['parent_uid'] && $credit2_dady>0){
						         	
						            $status1 = Member::updateCreditById($mems['parent_uid'], 0, $credit2_dady);
						            $status2 = CreditRecord::addInfo([
						                'uid' => $mems['parent_uid'],
						                'type' => 'credit2',
						                'num' => $credit2_dady,
						                'title' => '徒弟'.$mems['uid'].'首次完成任务奖励',
						                'remark' =>'徒弟'.$mems['uid'].'首次完成任务,奖励1元.',
						                'create_time' => TIMESTAMP
						            ]);
						            //添加纪录
			                		InvitationRebateRecord::addInfo([
			                            'uid' => $mems['parent_uid'],
			                            'num' => $credit2_dady,
			                            'task_id' => 0,
			                            'tuijian_id' =>$mems['uid'],
			                            'remark' => '徒弟'.$mems['uid'].'首次完成任务,奖励1元.',
			                            'create_time' => TIMESTAMP
			                        ]);
						            
						            //给上上级的奖励
						            $grandpa=db('member')->find($mems['parent_uid']);
						            $credit2_grand = $setting['shiye'];
						            if($grandpa && $grandpa['parent_uid'] && $credit2_grand>0){
							         	
							            $status1 = Member::updateCreditById($grandpa['parent_uid'], 0, $credit2_grand);
							 
							            $status2 = CreditRecord::addInfo([
							                'uid' => $grandpa['parent_uid'],
							                'type' => 'credit2',
							                'num' => $credit2_grand,
							                'title' => '徒孙'.$mems['uid'].'首次完成任务奖励',
							                'remark' =>'徒孙'.$mems['uid'].'首次完成任务,奖励0.5元.',
							                'create_time' => TIMESTAMP
							            ]);
						            
							            //添加纪录
				                		InvitationRebateRecord::addInfo([
				                            'uid' => $grandpa['parent_uid'],
				                            'num' => $credit2_grand,
				                            'task_id' => 0,
				                            'tuijian_id' =>$mems['uid'],
				                            'remark' => '徒孙'.$mems['uid'].'首次完成任务,奖励0.5元.',
				                            'create_time' => TIMESTAMP
				                        ]);
							            
						            }
				         	}
	  		}
			
			
        	//记录每日
	         $userinfo = db('member')->where('uid',$joinInfo['uid'])->find();
	        if($userinfo['partition_status']==1){
	            $jackpot = db('jackpot')->where('uid',$joinInfo['uid'])->where('today_time',date('Ymd'))->find();
	            if($jackpot['num']>$userinfo['partition_num']){
	                $my_task_num['partition_num'] = $userinfo['partition_num']+1;
	            }
	            if($jackpot['num']==$userinfo['partition_num']+1){
	                	$my_task_num['partition_status']=2;
	            }
	        }
	     	 $my_task_num['over_task_num'] = $userinfo['over_task_num']+1;
	        db('member')->where('uid',$joinInfo['uid'])->update($my_task_num);
			
        }
         

		//发红包
		$redpackage=\db('redpackage')->where(['task_id'=>$params['id']])->find();
	
		
		if($redpackage && !$redpackage['is_over']){
				$has_send_money=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->sum('money');
				$has_send_number=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['neq',0]])->count();
	
				if($has_send_money <$redpackage['money']){
					
					//要发的红包
					$send_info=\db('redpackage_record')->where(['task_id'=>$params['id'],'uid'=>['eq',0]])->order('redpackage_record_id asc')->find();
					
					$left_money=$redpackage['money']-$has_send_money;
					
					if($send_info && $left_money>0){
						
							
							//是否最后一个用户
							if( ($has_send_number+1) == $redpackage['number'] ){
								\db('redpackage')->where(['task_id'=>$params['id']])->setField('is_over',1);
							}
							
							$get_money=$send_info['money'];
							
						     $credit2 = $joinMemberInfo['credit2']+$get_money;
					    
					       // $res1 = \db('member')->where(['uid'=>$joinInfo['uid']])->data(['credit2'=>$credit2])->update();
					          
					          $res1 = Member::updateCreditById($joinInfo['uid'], 0, $get_money);
					          
					            if(!$res1){
						            Db::rollback();
						            message('操作失败:-3','','error');
						        }
		
		
					        $creditdata = array(
					            'uid'=>$joinInfo['uid'],
					            'type'=>'credit2',
					            'num'=>'+'.$get_money,
					            'title'=>'完成任务获得红包',
					            'remark'=>'完成任务'.$params['id'].'获得红包'.$get_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            Db::rollback();
					            message('审核失败:-5','','error');
					        }
					        
					        $send_info['uid']=$joinInfo['uid'];
					        $send_info['add_time']=time();
					        
					       $res4 = \db('redpackage_record')->data($send_info)->update();
					        if(!$res4){
					            Db::rollback();
					            message('审核失败:-6','','error');
					        }
					}
				         
				}
		}
		
		

       	task_reward($joinMemberInfo,$params);
        Db::commit();
        
        	
        $next = db('task_join')->where('task_id',$joinInfo['task_id'])->where('status',2)->find();
        
		if($next){
			message('审核成功',"/home/mytaskaudit/view/id/".$next['id'].".html",'success');
		}else{
			message('审核成功',"/home/mytaskaudit/index/id/".$params['id'].".html",'success');
		}

    }

    public function nopass() {
        $member = $this->checkLogin();

        $id = floor(trim(params('id')));
      	$reason = trim(params('reason'));
		
        if(!check_id($id)){
            message('审核ID错误','','error');
        }
      if(empty($reason)){
       message('拒绝原因不能为空!','','error'); 
      }
        $joinInfo = \app\home\model\TaskJoin::getInfoById($id);
        if(empty($joinInfo)){
            message('审核不存在','','error');
        }
if($joinInfo['status'] != 2){
   message('任务已审核','','error');
      }
        if(!empty($joinInfo['thumbs'])){
            $joinInfo['thumbs'] = unserialize($joinInfo['thumbs']);
        }

        $params = \app\home\model\Task::getInfoById($joinInfo['task_id']);
        if(empty($params)){
            message('任务不存在','','error');
        }

        if(empty($this->member['uid']) || $params['uid'] != $this->member['uid']){
            message('任务不存在','','error');
        }

        $insert_task_id = $joinInfo['task_id'];

        Db::startTrans();

        $update = array(
            'status' => 4,
            'audit_time' => TIMESTAMP,
            'update_time' => TIMESTAMP,
          	'reason'=>$reason
        );
        $status = \app\home\model\TaskJoin::updateInfoById($id, $update);
        if(!$status){
            Db::rollback();
            message('审核失败:-1','','error');
        }

        Db::commit();
		$next = db('task_join')->where('task_id',$joinInfo['task_id'])->where('status',2)->find();
		if($next){
			message('审核成功',"/home/mytaskaudit/view/id/".$next['id'].".html",'success');
		}else{
			message('审核成功',"/home/mytaskaudit/index/id/".$params['id'].".html",'success');
		}
        
    }

}